<!--
 * @Author: lihaogn
 * @Date: 2021-05-23 09:07:13
 * @LastEditTime: 2022-05-28 13:44:49
 * @LastEditor: lihaogn
 * @Description: 用户管理
 * @FilePath: \lix-admin-client-vue2\src\views\system\user-manage\user-list\index.vue
-->

<template>
  <LixTableView :show-tool="true" :show-pagination="true">
    <!-- 工具栏 -->
    <template #tool-left>
      <!-- 新增 -->
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        size="small"
        @click="handleNewUser"
        >新增
      </el-button>
    </template>
    <template #tool-right>
      <!-- 导入 -->
      <el-button
        size="small"
        type="success"
        plain
        icon="el-icon-upload2"
        @click="importExcelDialogVisible = true"
        >导入
      </el-button>
      <!-- 导出 -->
      <el-button
        size="small"
        type="success"
        plain
        icon="el-icon-download"
        @click="exportDialogVisible = true"
        >导出
      </el-button>
      <!-- 打印 -->
      <el-button
        size="small"
        type="info"
        plain
        icon="el-icon-printer"
        :loading="printLoading"
        v-print="printObj"
        >打印</el-button
      >
      <LixTableSelectColumn
        :columns="columns"
        @change="handleTableColumnsChange"
      />
    </template>
    <!-- 表格 -->
    <template #table="{maxHeight}">
      <el-table
        id="userTable"
        :data="tableData"
        v-loading="loading"
        border
        :max-height="maxHeight"
      >
        <!-- 序号 -->
        <el-table-column label="#" type="index"></el-table-column>

        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="
            item.prop === 'status'
              ? '67px'
              : item.prop === 'operation'
              ? '180px'
              : ''
          "
        >
          <template slot-scope="scope">
            <el-tag
              v-if="item.prop == 'status'"
              effect="dark"
              :type="getUserStatusType(scope.row)"
              size="small"
            >
              {{ mapUserStatus(scope.row.status) }}
            </el-tag>
            <template v-else-if="item.prop == 'role'">
              <el-tag
                class="role-tag"
                size="small"
                v-for="item in scope.row.role"
              >
                {{ item.name }}
              </el-tag>
            </template>

            <span
              v-else-if="item.prop == 'createdAt' || item.prop == 'updatedAt'"
              >{{ scope.row[item.prop] | dateFilter }}</span
            >
            <template v-else-if="item.prop === 'operation'">
              <el-button
                v-if="showOperation(scope.row)"
                type="text"
                size="medium"
                @click="handleEdit(scope.row)"
              >
                修改
              </el-button>

              <el-popconfirm
                v-if="showOperation(scope.row)"
                v-permission="['userDelete']"
                style="margin-left:10px;"
                placement="top"
                icon="el-icon-info"
                icon-color="red"
                title="确认删除？"
                @confirm="handleDelete(scope.row)"
              >
                <el-button slot="reference" type="text" size="medium"
                  >删除
                </el-button>
              </el-popconfirm>

              <el-dropdown
                v-if="showOperation(scope.row)"
                trigger="click"
                @command="command => handleTableRowCommand(scope.row, command)"
                style="margin-left: 10px"
              >
                <span class="el-dropdown-link el-button--text">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="4">修改密码</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status !== 1" command="1"
                    >启用</el-dropdown-item
                  >
                  <el-dropdown-item v-if="scope.row.status !== 2" command="2"
                    >停用</el-dropdown-item
                  >
                  <el-dropdown-item v-if="scope.row.status !== 3" command="3"
                    >注销</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!-- 分页 -->
    <template #pagination>
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 30]"
        :total="total"
        :page-size.sync="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </template>

    <!-- 新增/修改用户对话框 -->
    <NewOrUpdateUserDialog
      :visible.sync="adminDialogVisible"
      :type="operationType"
      :dialog-data="dialogData"
      @ok="getUserInfoList"
    />
    <!-- 修改密码对话框 -->
    <EditPasswordDialog
      :visible.sync="editPasswordDialogVisible"
      :editId="editUserId"
      @ok="getUserInfoList"
    />
    <!-- 导入对话框 -->
    <ImportExcelDialog
      :visible.sync="importExcelDialogVisible"
      title="导入用户"
      @ok="getUserInfoList"
    />
    <!-- 导出对话框 -->
    <LixExport
      :visible.sync="exportDialogVisible"
      title="导出用户"
      :request="getUserInfos"
    />
  </LixTableView>
</template>
<script>
// 请求接口方法
import {
  reqGetUserList,
  reqGetUserListByPage,
  reqEditUser,
  reqDeleteUser
} from '../../../../api/user-manage/user/api'
import NewOrUpdateUserDialog from './modules/NewOrUpdateUserDialog.vue'
import EditPasswordDialog from './modules/EditPasswordDialog.vue'
import ImportExcelDialog from '../../../../components/common/lix-import/ImportExcelDialog.vue'
import LixExport from '../../../../components/common/lix-export/index.vue'
import { commonMixin } from '../../../../mixins/common'
import LixTableView from '../../../../components/template/lix-table-view/index.vue'
import { USER_STATUS } from '../../../../constant'
import LixTableSelectColumn from '../../../../components/common/lix-table-select-column/index.vue'
import { mapGetters } from 'vuex'
export default {
  name: 'userInfo',
  mixins: [commonMixin],
  components: {
    NewOrUpdateUserDialog,
    EditPasswordDialog,
    ImportExcelDialog,
    LixExport,
    LixTableView,
    LixTableSelectColumn
  },
  data() {
    return {
      columns: [
        {
          label: '用户名',
          prop: 'name'
        },
        {
          label: '真实姓名',
          prop: 'realname'
        },
        {
          label: '角色',
          prop: 'role'
        },
        {
          label: '手机号码',
          prop: 'mobile'
        },
        {
          label: '邮箱',
          prop: 'email'
        },
        {
          label: '状态',
          prop: 'status'
        },
        {
          label: '创建时间',
          prop: 'createdAt'
        },
        {
          label: '修改时间',
          prop: 'updatedAt'
        },
        {
          label: '操作',
          prop: 'operation'
        }
      ],
      tableColumns: [],
      tableData: [],
      loading: false,
      editUserId: '',
      renameDialogVisible: false,
      editPasswordDialogVisible: false,
      adminDialogVisible: false,
      importExcelDialogVisible: false,
      exportDialogVisible: false,
      offerRoleDialogVisible: false,
      okBtnLoadingFlag: false,
      oldName: '',
      currentUserId: localStorage.getItem('userId'),
      // 数据总数
      total: 0,
      pageSize: 10,
      // 当前页
      currentPage: 1,
      printLoading: false,
      printObj: {
        // 打印区域
        id: 'userTable',
        // 打印标题
        popTitle: '用户列表',
        // 打印前
        beforeOpenCallback(vue) {
          this.printLoading = true
        },
        // 执行打印
        openCallback(vue) {
          this.printLoading = false
        }
      },
      // 操作类型
      operationType: 'NEW',
      // 传递给对话框的数据
      dialogData: {}
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created() {
    // 获取用户信息
    this.getUserInfoList()
  },
  mounted() {},
  methods: {
    /**
     * @author: lihaogn
     * @Date: 2022-05-28 13:25:48
     * @LastEditTime:
     * @description: 是否显示操作按钮
     * @param {*} row:Object - 行数据
     * @return {*}
     */

    showOperation(row) {
      if (row.role.some(r => r.id === '001')) {
        // 行数据中角色是超级管理员
        if (this.userInfo.role.some(r => r.id === '001')) {
          // 当前用户是管理员
          return true
        }
        return false
      }
      return true
    },
    /**
     * @author: lihaogn
     * @Date: 2021-12-26 16:02:06
     * @description: 选择列事件
     * @param {*} columns:Array - 选择到的列
     * @return {*}
     */
    handleTableColumnsChange(columns) {
      this.tableColumns = columns
    },
    /**
     * @author: lihaogn
     * @Date: 2021-12-19 22:02:11
     * @description: 新增用户按钮事件
     * @param {*}
     * @return {*}
     */

    handleNewUser() {
      this.operationType = 'NEW'
      this.adminDialogVisible = true
    },
    /**
     * @description: 映射用户状态
     * @param {*} status：用户状态码
     * @return {*}
     */
    mapUserStatus(status) {
      switch (status) {
        case USER_STATUS.ON:
          return '启用'
        case USER_STATUS.OFF:
          return '停用'
        case USER_STATUS.DEAD:
          return '注销'
        default:
          break
      }
    },

    handleEdit(row) {
      this.dialogData = row
      this.operationType = 'EDIT'
      this.adminDialogVisible = true
    },
    /**
     * @description: 修改用户状态（停用和注销时）
     * @param {*} command
     * @return {*}
     */
    editUserStatus(command) {
      let tipInfo = ''
      let statusCode = 0
      if (command === '2') {
        tipInfo = '停用'
        statusCode = 2
      } else if (command === '3') {
        tipInfo = '注销'
        statusCode = 3
      }
      if (this.editUserId === this.currentUserId) {
        // 改变用户账号的状态
        this.$confirm(`${tipInfo}后将退出登录，确认${tipInfo}？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            await reqEditUser(this.editUserId, {
              userStatus: statusCode,
              type: 'editStatus'
            })
          })
          .catch(() => {})
      } else {
        // 停用其他账户的情况
        this.$confirm(`确认${tipInfo}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const res = await reqEditUser(this.editUserId, {
              userStatus: statusCode,
              type: 'editStatus'
            })
            if (res.success) {
              this.$message.success(`已${tipInfo}`)
              this.getUserInfoList()
            }
          })
          .catch(() => {})
      }
    },
    /**
     * @description: 表格行操作-更多操作
     * @param {*} command
     * @return {*}
     */
    async handleTableRowCommand(row, command) {
      this.editUserId = row.id
      if (command === '1') {
        // 启用操作
        const res = await reqEditUser(this.editUserId, {
          userStatus: 1,
          type: 'editStatus'
        })
        if (res.success) {
          this.$message.success('已启用')
          this.getUserInfoList()
        }
      } else if (command === '2' || command === '3') {
        this.editUserStatus(command)
      } else if (command === '4') {
        // 修改密码
        this.editPassword(row)
      }
    },
    /**
     * @description: 获取用户状态类别
     * @param {*} row - 行数据
     * @return {*}
     */
    getUserStatusType(row) {
      if (row.status === USER_STATUS.ON) {
        return ''
      } else if (row.status === USER_STATUS.OFF) {
        return 'warning'
      } else {
        return 'info'
      }
    },

    /**
     * @description: 修改密码
     * @param {*} row
     * @return {*}
     */
    editPassword(row) {
      this.editUserId = row.id
      this.editPasswordDialogVisible = true
    },

    /**
     * @description: 重命名操作
     * @param {*} row
     * @return {*}
     */
    rename(row) {
      this.oldName = row.name
      this.editUserId = row.id
      this.renameDialogVisible = true
    },
    /**
     * @description: 表格行删除事件
     * @param {row:表格行数据}
     * @return {*}
     */
    async handleDelete(row) {
      const res = await reqDeleteUser(row.id)
      if (res.success) {
        this.$message.success(res.message)
        this.getUserInfoList()
      } else {
        this.$message.error(res.message)
      }
    },
    /**
     * @description: 获取用户信息
     * @param {*}
     * @return {*}
     */
    async getUserInfoList() {
      this.loading = true
      const res = await this.getUserInfos(false)
      if (res !== false) {
        this.tableData = res.result.data
        this.total = res.result.total
      }
      this.loading = false
    },
    /**
     * @author: lihaogn
     * @Date: 2021-12-08 16:06:59
     * @description:
     * @param {*} size - 页面数据量
     * @return {*}
     */
    handleSizeChange(size) {
      this.getUserInfoList()
    },
    /**
     * @author: lihaogn
     * @Date: 2021-12-08 16:07:03
     * @description:
     * @param {*} currentPage - 当前页码
     * @return {*}
     */
    handleCurrentChange(currentPage) {
      this.getUserInfoList()
    },
    /**
     * @author: lihaogn
     * @Date: 2021-12-08 16:21:42
     * @description: 获取用户信息数据
     * @param {*} type:Boolean - 获取方式: true-全部; false-分页;
     * @return {*}
     */
    async getUserInfos(type) {
      let res
      if (type) {
        res = await reqGetUserList()
      } else {
        res = await reqGetUserListByPage({
          page: this.currentPage,
          size: this.pageSize
        })
      }
      if (res.success) {
        return res
      } else {
        return false
      }
    },
    offerRole(row) {
      this.$message.info('该功能正在开发中。。。')
      this.offerRoleDialogVisible = true
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.el-form-item__content {
  flex-grow: 1;
}
.el-dropdown-link {
  cursor: pointer;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.role-tag {
  margin-right: 4px;
}
</style>
